package com.example.administrator.im.ui.activity;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.im.R;
import com.example.administrator.im.adapter.SearchFriendAdapter;
import com.example.administrator.im.data.SearchFriendData;
import com.example.administrator.im.db.FriendDBHelper;
import com.example.administrator.im.json.ResultJson;
import com.example.administrator.im.json.SearchFriendJson;
import com.example.administrator.im.utils.EMUtils;
import com.example.administrator.im.utils.HttpUtils;
import com.google.gson.Gson;

import org.litepal.LitePal;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * create:2018/10/2 16:17
 * author: 姚鸿杰
 **/
public class SearchFriendActivity extends MySlideFinishActivity {

    private final String TAG = "SearchFriendActivity";

    private EditText et_serch;

    private RecyclerView rv_search;
    private SearchFriendAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_friend);

        initView();
    }

    private void initView() {

        rv_search = (RecyclerView) findViewById(R.id.rv_search);
        rv_search.setLayoutManager(new LinearLayoutManager(this));
        adapter = new SearchFriendAdapter(null, this);
        rv_search.setAdapter(adapter);

        et_serch = (EditText) findViewById(R.id.search_friend);
        et_serch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                //变化前
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //变化中
            }

            @Override
            public void afterTextChanged(Editable s) {
                //变化后

                //获取用户输入的字段
                String content = s.toString();
                if (!TextUtils.isEmpty(content)) {
                    //去数据库匹配字段
                    List<FriendDBHelper> friends = LitePal.where("username like ?", "%" + content + "%").find(FriendDBHelper.class);
                    List<SearchFriendData> data = new ArrayList<>();
                    for (FriendDBHelper friend : friends) {
                        data.add(new SearchFriendData(friend.getUsername(), friend.getNickname(), content,
                                HttpUtils.PORT + friend.getImg_path()));
                    }
                    //匹配后添加到recyclerview
                    adapter.setmList(data);
                } else {
                    adapter.setmList(null);
                }

            }
        });
    }

    public void exit(View v) {
        finish();
    }

    public void search_friend(View v) {

        //如果adapter有数据则不搜索
        if (adapter.getItemCount() != 0) {
            return;
        }

        final String friend_id = et_serch.getText().toString();
        //判断有没有11位没有也不搜索
        if (friend_id.length() == 11) {

            SharedPreferences spf = getSharedPreferences("user", Context.MODE_PRIVATE);
            String username = spf.getString("username","");
            if(TextUtils.equals(username,friend_id)){
                //待添加自己信息
                return;
            }

            HttpUtils.getFriendRequest(friend_id, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e(TAG, e.getMessage());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {

                    String content = response.body().string();
                    Gson gson = new Gson();
                    ResultJson json = gson.fromJson(content, ResultJson.class);
                    if (json.getCode() == HttpUtils.SUCCESS) {

                        SearchFriendJson searchFriendJson = gson.fromJson(content, SearchFriendJson.class);
                        SearchFriendData data = new SearchFriendData(searchFriendJson.getData().getUsername(),
                                searchFriendJson.getData().getNickname(),
                                "", HttpUtils.PORT + searchFriendJson.getData().getImg_path());
                        final List<SearchFriendData> list = new ArrayList<>();
                        list.add(data);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                adapter.setmList(list, new SearchFriendAdapter.AddFriendListener() {
                                    @Override   //点击添加好友操作
                                    public void addFriendListener() {

                                        final AlertDialog alert_signature = getAlertDialog("添加好友", "添加理由");
                                        dialog_yes.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                EMUtils.addFriend(friend_id, et_reason.getText().toString());

                                                alert_signature.dismiss();
                                            }
                                        });
                                    }
                                });
                            }
                        });


                    } else if (json.getCode() == HttpUtils.SUCCESS_NO_CONTENT) {
                        Log.e(TAG, json.getData().toString());
                        //提示用户不存在
                    }

                }
            });

        } else {
            Toast.makeText(this, "未搜索到任何结果!!!", Toast.LENGTH_SHORT).show();
        }

    }


    private EditText et_reason;
    private Button dialog_yes;

    private View getDialogLayout(String title, String hint) {

        LayoutInflater inflater = this.getLayoutInflater();
        View view_custom = inflater.inflate(R.layout.dialog_add_group, null, false);
        TextView tv_title = view_custom.findViewById(R.id.dialog_tv_title);

        et_reason = view_custom.findViewById(R.id.dialog_et_name);
        et_reason.setHint(hint);
        et_reason.setMaxLines(3);
        et_reason.setFilters(new InputFilter[]{new InputFilter.LengthFilter(45)}); //最大输入长度

        tv_title.setText(title);
        dialog_yes = (Button) view_custom.findViewById(R.id.dialog_yes);
        return view_custom;
    }

    private AlertDialog getAlertDialog(String title, String hint) {
        View v = getDialogLayout(title, hint);
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setView(v);
        final AlertDialog alert = builder.create();
        alert.show();

        v.findViewById(R.id.dialog_no).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alert.dismiss();
            }
        });
        return alert;
    }


}
